//
//  RegisterViewController.m
//  citzenWorkStation
//
//  Created by yang qing on 2018/3/5.
//  Copyright © 2018年 yang qing. All rights reserved.
//

#import "RegisterViewController.h"
#import "CommonReqManage.h"
#import "UserInfoBean.h"
#import "NSObject+YYModel.h"
#import "ProtocolViewController.h"
@interface RegisterViewController (){
    dispatch_source_t _timer;
}
@property (weak, nonatomic) IBOutlet UITextField *tfPhoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *tfMsgCode;
@property (weak, nonatomic) IBOutlet UITextField *tfPsw;
@property (weak, nonatomic) IBOutlet UITextField *tfPswConfirm;
@property (weak, nonatomic) IBOutlet UIButton *btnMsgCode;
@property (weak, nonatomic) IBOutlet UIButton *btnRegister;
@property (weak, nonatomic) IBOutlet UIImageView *imgCheck;
@property (weak, nonatomic) IBOutlet UILabel *labUserDelegate;

@property (assign,nonatomic) BOOL agressDelegate;

@end

@implementation RegisterViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initLisnter];
    
}
- (void)initLisnter{
    _imgCheck.userInteractionEnabled = YES;
    UIGestureRecognizer *checkTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkClick)];
    [_imgCheck addGestureRecognizer:checkTap];
    
    
    [_btnRegister addTarget:self action:@selector(registerClick) forControlEvents:UIControlEventTouchUpInside];
    
    
     [self.btnMsgCode addTarget:self action:@selector(sendMsgCode) forControlEvents:UIControlEventTouchUpInside];
    
    _labUserDelegate.userInteractionEnabled= YES;
    UIGestureRecognizer *protocol = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(protocolClick)];
    [_labUserDelegate addGestureRecognizer:protocol];
}

- (void)protocolClick{
//    [self showToast:@"ok"];
    ProtocolViewController *proVc = [[ProtocolViewController alloc] init];
    [self.navigationController pushViewController:proVc animated:YES];
}


- (void)registerClick{
    if([self checkData]){
        [self showHub:@""];
        UserInfoBean *userInfo = [[UserInfoBean alloc] init];
        userInfo.phoneNumber = _tfPhoneNumber.text;
        userInfo.verifyCode = _tfMsgCode.text;
        userInfo.loginName = _tfPhoneNumber.text;
        userInfo.password = _tfPswConfirm.text;
        
        id param = [userInfo yy_modelToJSONObject];
        
        [CommonReqManage userRegister:param success:^(id success) {
             [self hiddenHub];
            NSString *status =  success[@"status"];
            if([status isEqualToString:@"1"]){
                [self showToast:@"注册成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self showTip:success[@"message"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
            }
        } failed:^(id faiure) {
            [self hiddenHub];
            [self showHubAuto:@"请求失败"];
        }];
        
    }
}


- (void)sendMsgCode{
    //请求网络发送验证码
    if([_tfPhoneNumber.text isEqualToString:@""]){
        [self showToast:@"请输入手机号"];
        return;
    }
    
    [CommonReqManage getMesgCode:_tfPhoneNumber.text success:^(id success) {
        NSString *status =  success[@"status"];
        if([status isEqualToString:@"1"]){
            [self countDown];
        }else{
            [self showTip:success[@"message"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
        }
    } failed:^(id failure) {
        NSLog(@"failur");
        [self showHubAuto:@"请求失败"];
    }];
}

//放这儿就报错 ？
- (void)countDown{
//    dispatch_source_t _timer;
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_btnMsgCode setTitle:@"发送验证码" forState:UIControlStateNormal];
                //设置不可点击
                _btnMsgCode.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [_btnMsgCode setTitle:[NSString stringWithFormat:@"重新发送(%@)",strTime] forState:UIControlStateNormal];
                //设置可点击
                _btnMsgCode.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


- (BOOL)checkData{
    if(!_agressDelegate){
        [self showToast:@"您需要同意用户协议才能注册"];
        return NO;
    }
    
    if([_tfPhoneNumber.text isEqualToString:@""]){
         [self showToast:@"手机号不能为空"];
        return NO;
    }
    
    
    if([_tfMsgCode.text isEqualToString:@""]){
        [self showToast:@"验证码不能为空"];
        return NO;
    }
    
    if([_tfPsw.text isEqualToString:@""]){
        [self showToast:@"密码不能为空"];
        return NO;
    }
    
    if([_tfPswConfirm.text isEqualToString:@""]){
        [self showToast:@"确认密码不能为空"];
        return NO;
    }
    
    if(![_tfPsw.text isEqualToString:_tfPswConfirm.text]){
        [self showToast:@"两次输入密码不一致"];
        return NO;
    }
    
    return YES;
}

- (void)checkClick{
    _agressDelegate = !_agressDelegate;
    [self changeAgressStatus:_agressDelegate];
}


- (void)initView{
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"用户注册";
    [self tfAddLeftImg:_tfPhoneNumber ImageName:@"icon_phone"];
    _tfPhoneNumber.keyboardType = UIKeyboardTypePhonePad;
    [self tfAddLeftImg:_tfMsgCode ImageName:@"icon_code"];
    _tfMsgCode.keyboardType = UIKeyboardTypeNumberPad;
    [self tfAddLeftImg:_tfPsw ImageName:@"icon_pwd"];
     [self tfAddLeftImg:_tfPswConfirm ImageName:@"icon_pwd"];
    _tfPswConfirm.secureTextEntry=YES;
    _tfPsw.secureTextEntry = YES;
    //设置按钮边框
    [_btnMsgCode.layer setMasksToBounds:YES];
    [_btnMsgCode.layer setBorderWidth:1.0];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpace, (CGFloat[]){ 88/255.0, 158/255.0, 248/255.0, 1 });
    [_btnMsgCode.layer setBorderColor:color];
    _btnMsgCode.contentEdgeInsets = UIEdgeInsetsMake(8, 10, 8, 10);
    _agressDelegate = NO;
    [self changeAgressStatus:_agressDelegate];
}

- (void)changeAgressStatus:(BOOL)status{
    if(status){
        [_imgCheck setImage:[UIImage imageNamed:@"icon_agreed"]];
    }else{
         [_imgCheck setImage:[UIImage imageNamed:@"icon_agreed_no"]];
    }
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if(_timer!=nil){
        dispatch_source_cancel(_timer);
    }
}

@end
